﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using IncrementalBackups.Properties;
using Ionic.Zip;
using System.Linq;
using IncrementalBackups.Helpers;
using System.Diagnostics;

namespace IncrementalBackups
{
    public partial class MainForm : Form
    {
        private FilesDS.FileListDataTable _scanedFileList = new FilesDS.FileListDataTable();
        private FilesDS.FileListDataTable _copyScanedFileList = new FilesDS.FileListDataTable();
        private BackupConfiguration _configuration = new BackupConfiguration();
        private string _appConfigFile = Path.Combine(Application.StartupPath, "config.xml");
        private BackupFile _restoreFile;
        private string _totalSizeOutPutDir = string.Empty;
        public string AppConfigFile
        {
            get { return _appConfigFile; }
            set { _appConfigFile = value; }
        }
        private string _outputFileName = "1-ListFiles.xml";
        private string _outputFileNameCSV = "2-ListFiles.csv";
        private string _configFile = "backupConfig.xml";
        private string _shortcutFileName = "restore backup {0}.mbsc";
        private string _destentionPath = " ";

        private Stopwatch _backupTime;

        private string _formatDateDirctory = "yyyy-MM-dd-hh-mm";

        #region  Public Properties

        public NotifyIcon NotifyIcon
        {
            get { return ntfyAppIcon; }
        }

        #endregion

        #region constrator

        public MainForm()
        {
            InitializeComponent();
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = "dd/MM/yyyy";
            lblConfigInfo.Text = string.Empty;
        }

        #endregion

        private void LoadConfiguration()
        {

            string path = _appConfigFile;
            if (File.Exists(path))
            {
                try
                {
                    _configuration.Clear();
                    _configuration.ReadXml(path);
                    txtDes.Text = _configuration.Configuration[0].OutputFolder;
                    dateTimePicker1.Value = _configuration.Configuration[0].LastDate;
                    cbRar.Checked = _configuration.Configuration[0].Rar;
                    cbZip.Checked = _configuration.Configuration[0].Zip;
                    if (!string.IsNullOrEmpty(_configuration.Configuration[0].NumberOfFiles))
                    {
                        lblConfigInfo.Text = string.Format("This config create {0} last run copy {1} file(s)", _configuration.Configuration[0].LastRunDate
                            , _configuration.Configuration[0].NumberOfFiles);
                    }
                    else
                    {
                        lblConfigInfo.Text = string.Format("This config create {0}", _configuration.Configuration[0].LastRunDate);
                    }
                    SourceFolder.CleatList();
                    if (_configuration.SlectedFolders.Rows.Count > 0)
                    {
                        List<string> foldersPath = new List<string>();
                        foreach (BackupConfiguration.SlectedFoldersRow dr in _configuration.SlectedFolders.Rows)
                        {
                            foldersPath.Add(dr.FolderPath);
                        }
                        SourceFolder.AddFoldersPath(foldersPath);
                    }
                }
                catch (Exception ex)
                {
                    LogsHelper.WriteToErrorLog(ex, "Error load config file: " + path, false);
                    MessageBox.Show("The Backup System can't load the config file!", "Exit Backup System?", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        /// <summary>
        /// Exits the application.
        /// </summary>
        private static void ExitApplication()
        {
            DialogResult dr = MessageBox.Show("Are you sure you want to exit the Backup System?", "Exit Backup System?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
                Application.Exit(new CancelEventArgs(false));
        }

        #region Menu  events

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExitApplication();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new BackupSystemAbout().ShowDialog();
        }

        private void viewErrorLogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LogsHelper.OpenLog(LogsType.Error);
        }

        private void viewEventLogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LogsHelper.OpenLog(LogsType.Event);
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveCnnfiguration(_appConfigFile);
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ValidateControls(false))
            {
                saveConfigDialog.FileName = string.Format("config{0}", DateTime.Now.Date.ToString(Resources.FormatShotDateValidFolderName));
                DialogResult dr = saveConfigDialog.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    BackupConfiguration dt = new BackupConfiguration();
                    BackupConfiguration.ConfigurationRow cdr = dt.Configuration.AddConfigurationRow
                       (dateTimePicker1.Value.Date, DateTime.Now, cbZip.Checked, cbRar.Checked, txtDes.Text, null);
                    foreach (string dirPath in SourceFolder.GetFilePathsList())
                    {
                        dt.SlectedFolders.AddSlectedFoldersRow(cdr, dirPath);
                    }
                    dt.WriteXml(saveConfigDialog.FileName);
                }
            }
            else
            {
                MessageBox.Show("You can't save unvalid config", Resources.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        #endregion

        #region Private methods

        private void WriteConfigToEventLog(EventType eventType, BackupConfiguration.ConfigurationRow configurationRow)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Format("LastRunDate: {0} |", configurationRow.LastRunDate));
            if (!string.IsNullOrEmpty(configurationRow.NumberOfFiles))
                sb.Append(string.Format("Number Of files: {0} |", configurationRow.NumberOfFiles));
            sb.Append(string.Format("LastDate: {0} |", configurationRow.LastDate.Date));
            sb.Append(string.Format("Zip: {0} |", configurationRow.Zip));
            sb.Append(string.Format("Rar: {0} |", configurationRow.Rar));
            sb.Append(string.Format("OutputFolder: {0} |", configurationRow.OutputFolder));
            sb.Append(string.Format("Backup folder: {0} |", Path.GetFileName(_destentionPath)));
            LogsHelper.WriteToEventLog(string.Format("{0} |config: {1}", eventType, sb.ToString()));
        }

        private void SaveCnnfiguration(string configDestantion)
        {
            //Clear Config from old data
            if (ComperConfig())
            {
                _configuration.Clear();
                _configuration.Configuration.Clear();
                _configuration.SlectedFolders.Clear();
                BackupConfiguration.ConfigurationRow cdr = _configuration.Configuration.AddConfigurationRow
                    (dateTimePicker1.Value.Date, DateTime.Now, cbZip.Checked, cbRar.Checked, txtDes.Text, null);
                foreach (string dirPath in SourceFolder.GetFilePathsList())
                {
                    _configuration.SlectedFolders.AddSlectedFoldersRow(cdr, dirPath);
                }
            }
            _configuration.WriteXml(configDestantion);

        }

        private bool ComperConfig()
        {
            bool result = false;
            if (_configuration.Configuration.Count == 0)
                result = true;
            else
            {
                BackupConfiguration.ConfigurationDataTable dt = new BackupConfiguration.ConfigurationDataTable();
                BackupConfiguration.ConfigurationRow cdr = dt.AddConfigurationRow
                        (dateTimePicker1.Value.Date, DateTime.Now, cbZip.Checked, cbRar.Checked, txtDes.Text, null);
                if (!_configuration.Configuration[0].LastDate.Equals(cdr.LastDate))
                {
                    result = true;
                }
                if (!_configuration.Configuration[0].OutputFolder.Equals(cdr.OutputFolder))
                {
                    result = true;
                }
                if (!_configuration.Configuration[0].Rar.Equals(cdr.Rar))
                {
                    result = true;
                }
                if (!_configuration.Configuration[0].Zip.Equals(cdr.Zip))
                {
                    result = true;
                }
                if (_configuration.SlectedFolders.Count != SourceFolder.GetFilePathsList().Count)
                    result = true;
                else
                {
                    foreach (string dirPath in SourceFolder.GetFilePathsList())
                    {
                        if (!_configuration.SlectedFolders.Any(dir => dir.FolderPath.Equals(dirPath)))
                        {
                            result = true;
                            break;
                        }
                    }
                }
            }
            return result;
        }

        private void UpdateConfigurationWithNumberOfFiles(string number)
        {
            if (_configuration.Configuration.Count > 0)
            {
                _configuration.Configuration[0].NumberOfFiles = number;
                _configuration.WriteXml(_appConfigFile);
            }
        }

        private bool ValidateControls(bool checkDesDir)
        {
            epInputs.Clear();
            bool result = true;
            if (dateTimePicker1.Value.Date > DateTime.Now.Date)
            {
                result = false;
                epInputs.SetError(dateTimePicker1, "You can't backup the future");
                epInputs.SetIconPadding(dateTimePicker1, -33);
            }
            if (SourceFolder.GetFilePathsList().Count <= 0)
            {
                result = false;
                epInputs.SetError(SourceFolder, Resources.emptyFolders);
                epInputs.SetIconAlignment(SourceFolder, ErrorIconAlignment.MiddleRight);
                epInputs.SetIconPadding(SourceFolder, -22);
                lblStatus.Text = Resources.emptyFolders;
            }
            else
            {
                foreach (string fname in SourceFolder.GetFilePathsList())
                {
                    if (SourceFolder.GetFilePathsList().Count(f => f.Equals(fname)) > 1)
                    {
                        result = false;
                        epInputs.SetError(SourceFolder, "duplicated folder");
                        epInputs.SetIconAlignment(SourceFolder, ErrorIconAlignment.MiddleRight);
                        epInputs.SetIconPadding(SourceFolder, -22);
                        break;
                    }
                }
            }
            if (!string.IsNullOrEmpty(txtDes.Text))
            {
                string baclupDirName = Path.Combine(txtDes.Text,
                string.Format(Resources.DestentionFolderFormat, DateTime.Now.ToString(_formatDateDirctory), dateTimePicker1.Value.Date.ToString(Resources.FormatShotDateValidFolderName)));
                baclupDirName = Path.Combine(baclupDirName, "Files");
                if (SourceFolder.GetFilePathsList().Any(dir => dir == txtDes.Text.Trim()))
                {
                    result = false;
                    epInputs.SetError(txtDes, "Destination folder can't be scan folder");
                    epInputs.SetIconPadding(txtDes, -22);
                    epInputs.SetError(SourceFolder, "One folder is the destination folder");
                    epInputs.SetIconAlignment(SourceFolder, ErrorIconAlignment.MiddleRight);
                    epInputs.SetIconPadding(SourceFolder, -22);

                }


                if (checkDesDir && result)
                {
                    if (Directory.Exists(baclupDirName))
                    {
                        DialogResult dr = MessageBox.Show(string.Format("{0}{1}{2}", baclupDirName, Environment.NewLine, "Dirctory is already exist do you want to delete all files in this folder and continue?"),
                            Resources.ProgramName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            Directory.Delete(baclupDirName, true);
                        }
                        else
                        {
                            result = false;
                            lblStatus.Text = string.Format("{0} {1}", Path.GetFileName(baclupDirName), "Dirctory is already exist");
                        }


                    }
                    if (result)
                        _destentionPath = Directory.CreateDirectory(baclupDirName).FullName;
                }
            }
            else
            {
                result = false;
                lblStatus.Text = Resources.emptyDes;
                epInputs.SetError(txtDes, Resources.emptyDes);
                epInputs.SetIconPadding(txtDes, -22);
            }
            if (!result)
            {
                epInputs.SetError(btnRun, "Backup can't run please check inputs");
                epInputs.SetIconAlignment(btnRun, ErrorIconAlignment.MiddleLeft);
            }
            return result;
        }
        #endregion

        #region buttons events

        private void btnSelectFolder_Click(object sender, EventArgs e)
        {
            DialogResult dr = folderDestination.ShowDialog();
            if (dr == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(folderDestination.SelectedPath))
                {
                    txtDes.Text = folderDestination.SelectedPath;
                }
            }
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            //Check all inputs.
            if (ValidateControls(true))
            {
                _backupTime = new Stopwatch();
                _backupTime.Start();
                _scanedFileList.Clear();
                progressBar1.Value = 5;
                SaveCnnfiguration(_appConfigFile);
                WriteConfigToEventLog(EventType.Start, _configuration.Configuration[0]);
                progressBar1.Value = 10;
                progressBar1.Style = ProgressBarStyle.Marquee;
                lblStatus.Text = Resources.processingFiles;
                bwScanFiles.RunWorkerAsync();
            }
        }

        #endregion


        private void bwScanFiles_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                _scanedFileList.Clear();
                foreach (string dirPath in SourceFolder.GetFilePathsList())
                {
                    DirectoryInfo srcDir = new DirectoryInfo(dirPath);
                    ScanFiles(srcDir);
                }
            }
            catch (Exception ex)
            {
                LogsHelper.WriteToErrorLog(ex, "Error Scan files.", false);
            }

        }

        private void ScanFiles(DirectoryInfo srcDir)
        {

            foreach (FileInfo info in srcDir.GetFiles("*.*"))
            {
                if (info.LastWriteTime.Date.Date >= dateTimePicker1.Value.Date)
                {

                    DataRow[] quray = _scanedFileList.Select(string.Format("{0}='{1}'", "FileName", info.Name));
                    if (quray.Length == 0)
                        _scanedFileList.AddFileListRow(info.Name, info.DirectoryName, info.Name);
                    else
                    {
                        _scanedFileList.AddFileListRow(string.Format("{0}{1}", Guid.NewGuid().ToString(), info.Name), info.DirectoryName, info.Name);
                    }
                }

            }
            foreach (DirectoryInfo info3 in srcDir.GetDirectories())
            {
                this.ScanFiles(info3);
            }
        }

        private void bwScanFiles_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar1.Value = 20;
            lblStatus.Text = string.Format("Start copy files {0} scan time: {1} ", _scanedFileList.Count.ToString(), StopWacthTime);
            if (_scanedFileList.Count > 0)
            {
                bwCopyFiles.RunWorkerAsync();
            }
            else
            {
                lblStatus.Text = "There is no files to backup! ";
                WriteConfigToEventLog(EventType.End, _configuration.Configuration[0]);
                progressBar1.Style = ProgressBarStyle.Blocks;
                progressBar1.Value = 100;
            }
        }

        private void bwCopyFiles_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                _copyScanedFileList.Clear();
                foreach (FilesDS.FileListRow dr in _scanedFileList)
                {
                    if (File.Exists(Path.Combine(dr.Dirctory, dr.Original_FileName)))
                    {
                        if (!File.Exists(Path.Combine(_destentionPath, dr.FileName)) || cbOver.Checked)
                        {
                            File.Create(Path.Combine(_destentionPath, dr.FileName)).Dispose();
                            File.Copy(Path.Combine(dr.Dirctory, dr.Original_FileName), Path.Combine(_destentionPath, dr.FileName), true);
                            _copyScanedFileList.AddFileListRow(dr.FileName, dr.Dirctory, dr.Original_FileName);
                        }
                        else
                        {
                            DialogResult dres = MessageBox.Show(string.Format(Resources.fileExist, Path.Combine(_destentionPath, dr.FileName), Environment.NewLine), "Backup System", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (dres == DialogResult.Yes)
                            {
                                File.Copy(Path.Combine(dr.Dirctory, dr.Original_FileName), Path.Combine(_destentionPath, dr.FileName), true);
                                _copyScanedFileList.AddFileListRow(dr.FileName, dr.Dirctory, dr.Original_FileName);
                            }
                        }
                    }
                }
                if (_copyScanedFileList.Count > 0)
                {
                    //Build file list csv.
                    FilesDS.FileListRow dr = _copyScanedFileList.NewRow() as FilesDS.FileListRow;
                    dr.ID = 0;
                    dr.FileName = "File name in backup folder";
                    dr.Dirctory = "Source Dirctory";
                    dr.Original_FileName = "Original file name";
                    _copyScanedFileList.Rows.InsertAt(dr, 0);
                    Helper.WriteDataTableToCSV(_copyScanedFileList, Path.Combine(Path.GetDirectoryName(_destentionPath), _outputFileNameCSV));
                    _copyScanedFileList.Rows.RemoveAt(0);

                    //Count size of folder.
                    long totalSize = 0;
                    DirectoryInfo directory = new DirectoryInfo(_destentionPath);
                    FileInfo[] files = directory.GetFiles();
                    foreach (FileInfo file in files)
                    {
                        totalSize += file.Length;
                    }
                    _totalSizeOutPutDir = Helper.ConvertBytesToMegabytes(totalSize).ToString("0.##");

                }

                e.Result = true;
            }
            catch (Exception ex)
            {
                LogsHelper.WriteToErrorLog(ex, "Error copy files", false);
                e.Result = ex;
            }

        }



        private void bwCopyFiles_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            if (e.Result != null)
            {
                if (e.Result is bool && (bool)e.Result)
                {
                    DirectoryInfo di = new DirectoryInfo(_destentionPath);
                    progressBar1.Value = 70;
                    lblStatus.Text = string.Format(Resources.copyFiles, di.GetFiles().Length - 1, "Size: " + _totalSizeOutPutDir + " MB", StopWacthTime);
                    _backupTime = null;
                    if (!File.Exists(Path.Combine(_destentionPath, _outputFileName)) && _copyScanedFileList.Count > 0)
                    {
                        _copyScanedFileList.WriteXml(Path.Combine(Path.GetDirectoryName(_destentionPath), _outputFileName));
                        UpdateConfigurationWithNumberOfFiles(_copyScanedFileList.Count.ToString());
                        CreateApplicationFile();

                    }
                    if (cbZip.Checked && _copyScanedFileList.Count > 0)
                    {
                        lblStatus.Text = "Start zipping files";
                        bwZipFolder.RunWorkerAsync(_destentionPath);
                    }
                    else
                    {
                        WriteConfigToEventLog(EventType.succee, _configuration.Configuration[0]);
                        progressBar1.Style = ProgressBarStyle.Blocks;
                        progressBar1.Value = 100;
                    }
                }
                else if (e.Result is Exception)
                {
                    lblStatus.Text = "Error copying files";
                    WriteConfigToEventLog(EventType.Faild, _configuration.Configuration[0]);
                    progressBar1.Style = ProgressBarStyle.Blocks;
                    progressBar1.Value = 100;
                }

            }
        }

        private void CreateApplicationFile()
        {
            string fileLocation = Path.Combine(Path.GetDirectoryName(_destentionPath), string.Format(_shortcutFileName, DateTime.Now.ToString(Resources.FormatShotDateValidFolderName)));
            BackupFile bf = new BackupFile();
            bf.DestinationPath = _destentionPath;
            string helpString = Path.Combine(Path.GetDirectoryName(_destentionPath), _outputFileName);
            if (File.Exists(helpString))
                bf.OutputFilesXml = helpString;
            else
                throw new Exception("Error find list of files");
            helpString = Path.Combine(Path.GetDirectoryName(_destentionPath), _outputFileNameCSV);
            if (File.Exists(helpString))
                bf.OutputFilesCsv = helpString;
            else
                throw new Exception("Error find list of files csv");
            helpString = Path.Combine(Path.GetDirectoryName(_destentionPath), _configFile);
            _configuration.WriteXml(helpString);
            bf.BackupConfigFile = helpString;
            bf.NumberOfCopyFiles = _copyScanedFileList.Count;
            bf.WriteBackupFileToDisk(fileLocation);
        }


        #region Form's events

        private void MainForm_Load(object sender, EventArgs e)
        {
            LoadConfiguration();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                ntfyAppIcon.ShowBalloonTip(1000, Resources.ProgramName, "Incremental Backups still working...", ToolTipIcon.Info);
                this.Hide();
            }
        }

        #endregion

        /// <summary>
        /// Shows the form.
        /// </summary>
        private void ShowForm()
        {
            this.Show();
        }

        #region notify icon events

        private void ntfyAppIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowForm();
        }

        private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm();
        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ExitApplication();
        }
        #endregion

        private void bwZipFolder_DoWork(object sender, DoWorkEventArgs e)
        {
            if (e.Argument != null && !string.IsNullOrEmpty(e.Argument.ToString()))
            {
                string folder = e.Argument.ToString();
                DirectoryInfo di = new DirectoryInfo(folder);
                string zipFileName = Path.Combine(di.Parent.FullName, di.Name);
                if (Directory.Exists(folder))
                {
                    try
                    {
                        using (ZipFile zip = new ZipFile())
                        {
                            // add this map file into the "images" directory in the zip archive
                            zip.AddDirectory(folder);

                            zip.Save(string.Format("{0}.zip", zipFileName));
                            e.Result = true;
                        }
                    }
                    catch (Exception ex1)
                    {
                        if (File.Exists(zipFileName))
                            File.Delete(zipFileName);
                        LogsHelper.WriteToErrorLog(ex1, "Error compress zip file", false);
                        e.Result = ex1;

                    }
                }



            }


        }

        private void bwZipFolder_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar1.Style = ProgressBarStyle.Blocks;
            progressBar1.Value = 100;
            if (e.Result != null)
            {
                if (e.Result is bool)
                {
                    lblStatus.Text = "Done!";
                    WriteConfigToEventLog(EventType.succee, _configuration.Configuration[0]);
                }
                else if (e.Result is Exception)
                {
                }

            }

        }

        public bool ValidRestoreFile(string fileLocation)
        {
            bool result = true;
            string configFile = Path.Combine(Path.GetDirectoryName(fileLocation), _configFile);

            _restoreFile = new BackupFile();
            if (_restoreFile.LoadRestoreFile(fileLocation))
            {
                AppConfigFile = _restoreFile.BackupConfigFile;
                btnRestore.Visible = true;

            }
            return result;
        }

        private void backupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dr = openFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                try
                {
                    BackupConfiguration bconfig = new BackupConfiguration();
                    bconfig.ReadXml(openFileDialog1.FileName);
                    _appConfigFile = openFileDialog1.FileName;
                    LoadConfiguration();

                }
                catch (Exception ex)
                {
                    LogsHelper.WriteToErrorLog(ex, "Load config file: " + openFileDialog1.FileName, false);
                    MessageBox.Show("Can't load this config file", Resources.ProgramName, MessageBoxButtons.OK);
                }
            }
        }

        private void btnRestore_Click(object sender, EventArgs e)
        {
            if (_restoreFile != null)
            {
                lblStatus.Text = "Starting restore files";
                progressBar1.Style = ProgressBarStyle.Marquee;
                bwRestore.RunWorkerAsync();
            }

        }

        private void bwRestore_DoWork(object sender, DoWorkEventArgs e)
        {

        }

        private void bwRestore_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        public string StopWacthTime
        {
            get
            {
                if (_backupTime != null)
                {
                    if (_backupTime.Elapsed.TotalSeconds < 60)
                        return string.Format("{0} Seconds", Math.Ceiling(_backupTime.Elapsed.TotalSeconds));
                    else if (_backupTime.Elapsed.Minutes < 60)
                        return string.Format("{0} Minutes {1} Seconds", _backupTime.Elapsed.Minutes, Math.Ceiling(_backupTime.Elapsed.TotalSeconds));
                    else if (_backupTime.Elapsed.Hours > 1)
                        return string.Format("{0} Hours {1} Minutes {2} Seconds",
                            _backupTime.Elapsed.Hours, _backupTime.Elapsed.Minutes, _backupTime.Elapsed.Seconds);

                    return "Stop Wath didnt run.";
                }
                else
                    return "Stop Wath didnt run.";

            }
        }

        private void ntfyAppIcon_MouseMove(object sender, MouseEventArgs e)
        {
            if (bwCopyFiles.IsBusy || bwScanFiles.IsBusy)
            {
                ntfyAppIcon.ShowBalloonTip(3, "Incremental Backups", "Backup is running..", ToolTipIcon.Info);
            }

        }

        private void ntfyAppIcon_BalloonTipShown(object sender, EventArgs e)
        {
            // MessageBox.Show("Test");
        }

    }
}
